// pages/receivingAddress/receivingAddress.js
import deliveryApi from '../../service/deliveryApi'
import { checkPhone } from '../../utils/util'

const app = getApp()
let codeConfig = app.globalData.codeConfig
Page({

  /**
   * 页面的初始数据
   */
  data: {
    options1: [],
    adderssInfo: {
      userName: '',
      telephone: '',
      detailAddress: '',
      areaName: '',
      province: '',
      city: '',
      area: ''
    },
    operationHint: '', // 操作提示
    saveLoading: false, // 保存按钮文字前的loading
    delLoading: false, // 删除按钮文字前的loading
    disabled: true,
    operatType: 'add', // 操作类型
    fromType: 'address', // 来自哪个页面 order-订单页，address-地址列表页
    textareaShowFlag: false,
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    if (options.operatType) {
      this.setData({
        operatType: options.operatType
      })
    }
    if (options.operatType && options.operatType === 'update') {
      this.setData({
        'adderssInfo.userName': options.userName,
        'adderssInfo.telephone': options.telephone,
        'adderssInfo.detailAddress': options.detailAddress,
        'adderssInfo.addressId': options.addressId,
        'adderssInfo.areaName': options.areaName,
        'adderssInfo.province': options.province,
        'adderssInfo.city': options.city,
        'adderssInfo.area': options.area,
        disabled: false
      })
    }
    this.getData()
  },

  // 获取省市县三级数据
  getData() {
    let that = this
    deliveryApi.areaInfo().then(({ data }) => {
      that.setData({
        options1: JSON.parse(data.data)
      })
    })
  },
  onOpen1() {
    let that = this
    that.setData({ visible1: true })
    let param = setTimeout(function () {
      that.setData({
        textareaShowFlag: true
      })
    }, 100)
  },
  onClose1() {
    let that = this
    that.setData({ visible1: false })
    let param = setTimeout(function () {
      that.setData({
        textareaShowFlag: false
      })
    }, 100)
  },
  onChange1(e) {
    var _options = e.detail.options
    this.setData({ 
      'adderssInfo.areaName': _options.map((n) => n.label).join(' '),
      'adderssInfo.province': _options[0].value,
      'adderssInfo.city': _options[1] ? _options[1].value : '',
      'adderssInfo.area': _options[2] ? _options[2].value : ''
    })
    this.canClick()
  },
  // 保存按钮
  formSubmit(e) {
    var that = this
    var _form = that.data.adderssInfo
    if (_form.area === '') {
      wx.showToast({
        title: '请选择完整的地区',
        icon: 'none'
      })
      return false
    }
    // 校验表单
    if (!checkPhone(_form.telephone)){
      wx.showToast({
        title: '手机号格式不正确',
        icon: 'none'
      })
      return false
    }
    var params = {..._form}
    if (that.data.saveLoading) return
    that.setData({
      saveLoading: true
    })
    if (this.data.operatType === 'add') {
      this.onAddAddress(params)
    } else {
      this.onUploadAddress(params)
    }
  },

  // 添加
  onAddAddress(params) {
    var that = this
    deliveryApi.addAddress(params).then(({data}) => {
      wx.showLoading({
        title: '加载中...',
      })
      that.setData({
        saveLoading: false
      })
      if (data.errCode === codeConfig.errCode.SUCCESS_CODE) {
        wx.hideLoading()
        app.globalData.address = {...params, addressId: data.data.addressId}
        that.setData({
          operationHint: '收货地址已保存'
        })
        wx.navigateBack({ delta: 1 })
      } else {
        wx.showToast({
          title: data.msg,
          icon: 'none'
        })
      }
    }).catch((res) => {
      wx.hideLoading()
      that.setData({
        saveLoading: false
      })
    })
  },
  // 修改
  onUploadAddress(params) {
    var that = this
    deliveryApi.updateAddress(params).then(({data}) => {
      wx.showLoading({
        title: '加载中...',
      })
      that.setData({
        saveLoading: false
      })
      if (data.errCode === codeConfig.errCode.SUCCESS_CODE) {
        wx.hideLoading()
        that.setData({
          operationHint: '收货地址已保存'
        })
        if (params.addressId == app.globalData.address.addressId) {
          app.globalData.address = {...params}
        }
        wx.navigateBack({ delta: 1 })
      } else {
        wx.showToast({
          title: data.msg,
          icon: 'none'
        })
      }
    }).catch((res) => {
      wx.hideLoading()
      that.setData({
        saveLoading: false
      })
    })
  },
  // 删除按钮
  delAddress(e) {
    var that = this
    wx.showModal({
      content: '确认删除该收货地址？',
      confirmColor: '#FF2424',
      success(res) {
        if (res.confirm) {
          that.setData({
            delLoading: true
          })
          deliveryApi.delAddress({addressId: that.data.adderssInfo.addressId}).then(({ data }) => {
            if (data.errCode === codeConfig.errCode.SUCCESS_CODE) {
              if (that.data.adderssInfo.addressId == app.globalData.address.addressId) {
                app.globalData.address = {}
              }
              that.setData({
                operationHint: '删除成功'
              })
              wx.navigateBack({ delta: 1 })
            } else {
              that.setData({
                delLoading: false
              })
              wx.showToast({
                title: data.msg,
                icon: 'none'
              })
            }
          }).catch(res => {
            that.setData({
              delLoading: false
            })
          })
        }
      }
    })
  },

  getUserName (e) {
    this.setData({
      'adderssInfo.userName': e.detail.value
    })
    this.canClick()
  },
  getTelephone (e) {
    this.setData({
      'adderssInfo.telephone': e.detail.value
    })
    this.canClick()
  },
  getDeliveryAddress (e) {
    this.setData({
      'adderssInfo.detailAddress': e.detail.value
    })
    this.canClick()
  },

  // 保存按钮活性控制
  canClick () {
    var userName = this.data.adderssInfo.userName
    var telephone = this.data.adderssInfo.telephone
    var detailAddress = this.data.adderssInfo.detailAddress
    // var province = this.data.adderssInfo.province
    // var city = this.data.adderssInfo.city
    // var area = this.data.adderssInfo.area
    if (userName !== '' && telephone !== '' && detailAddress !== '') {
      this.setData({
        disabled: false
      })
    } else {
      this.setData({
        disabled: true
      })
    }
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {
    this.setData({
      operationHint: ''
    })
  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {
    let that = this
    if (that.data.operationHint !== '') {
      wx.showToast({
        title: that.data.operationHint,
        icon: 'none'
      })
    }
  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {
    let that = this
    if (that.data.operationHint !== '') {
      wx.showToast({
        title: that.data.operationHint,
        icon: 'none'
      })
    }
  }
})